<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理界面</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/layui/2.6.3/css/layui.css" media="all">
    <style>
        html,body{
            width: 100%;
            height: 100%;
            padding: 0;
            margin: 0;
        }
        body {
            background-color: #fff;
        }
        .layui-container{
            top: 60px;
        }
    </style>
</head>
<body>

<div class="layui-container">
    <!-- <div class="layui-row">
        <div class="layui-col-md12">
            <div class="layui-btn-group">
                <button class="layui-btn" id="addUser">添加用户</button>
                <button class="layui-btn layui-btn-normal" id="editUser">编辑用户</button>
                <button class="layui-btn layui-btn-danger" id="deleteUser">删除用户</button>
            </div>
        </div>
    </div> -->
    <div class="layui-row">
        <div class="layui-col-md12">
            <table id="userTable" lay-filter="userTable"></table>
        </div>
    </div>
</div>

<!-- 添加/编辑用户表单 -->
<div id="userForm" style="display: none;">
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
                <input type="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-block">
                <select name="role" required lay-verify="required">
                    <option value="admin">管理员</option>
                    <option value="user">普通用户</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机号</label>
            <div class="layui-input-block">
                <input type="text" name="phoneNum" required lay-verify="required|phone" placeholder="请输入手机号" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="saveUser">保存</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/layui/2.6.3/layui.js"></script>
<script>
    let requestHost = '/api';
    layui.use(['table', 'form', 'layer'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;

        // 渲染表格
        table.render({
            elem: '#userTable',
            url: requestHost + '/user/findAllLayuiTable', // 模拟数据接口
            cols: [[
                // {type: 'checkbox'},
                {field: 'username', title: '用户名'},
                {field: 'isPass', title: '状态(通过后可登录)', templet: function(d){
                    return d.isPass === '1'? '已通过': '-';
                }},
                {field: 'role', title: '角色', templet: function(d){
                    return d.role === 'ADMIN'? '管理员': d.role === 'DATA'? '数据用户': '普通用户';
                }},
                {field: 'phoneNum', title: '手机号'},
                {fixed: 'right', title: '操作', width: 250, align: 'center', toolbar: '#tableBar'}
            ]],
            page: true
        });

        // 监听工具条
        table.on('tool(userTable)', function(obj){
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;

            if(layEvent === 'edit'){
                openEditForm(data);
            } else if(layEvent === 'delete'){
                deleteUser(data.id);
            } else if(layEvent === 'shenhe'){
                shenheUser(data);
            } else if(layEvent === 'role'){
                roleUser(data);
            }
        });

        // // 添加用户按钮
        // document.getElementById('addUser').onclick = function(){
        //     openAddForm();
        // };

        // // 编辑用户按钮
        // document.getElementById('editUser').onclick = function(){
        //     var checkStatus = table.checkStatus('userTable');
        //     if(checkStatus.data.length !== 1){
        //         layer.msg('请选择一条数据进行编辑');
        //         return;
        //     }
        //     openEditForm(checkStatus.data[0]);
        // };

        // // 删除用户按钮
        // document.getElementById('deleteUser').onclick = function(){
        //     var checkStatus = table.checkStatus('userTable');
        //     if(checkStatus.data.length === 0){
        //         layer.msg('请选择要删除的数据');
        //         return;
        //     }
        //     deleteUser(checkStatus.data[0].id);
        // };

        // 打开添加表单
        function openAddForm(){
            layer.open({
                type: 1,
                area: ['400px', '400px'],
                title: '添加用户',
                content: document.getElementById('userForm').innerHTML,
                success: function(layero, index){
                    form.val('userForm', {
                        username: '',
                        password: '',
                        role: 'user',
                        phoneNum: ''
                    });
                },
                btn: ['保存', '取消'],
                yes: function(index, layero){
                    saveUser(index, null);
                },
                btn2: function(index, layero){
                    layer.close(index);
                }
            });
        }

        // 打开编辑表单
        function openEditForm(data){
            layer.open({
                type: 1,
                area: ['400px', '400px'],
                title: '编辑用户',
                content: document.getElementById('userForm').innerHTML,
                success: function(layero, index){
                    form.val('userForm', {
                        username: data.username,
                        password: data.password,
                        role: data.role,
                        phoneNum: data.phoneNum
                    });
                },
                btn: ['保存', '取消'],
                yes: function(index, layero){
                    saveUser(index, data.id);
                },
                btn2: function(index, layero){
                    layer.close(index);
                }
            });
        }

        // 保存用户
        form.on('submit(saveUser)', function(data){
            var formData = data.field;
            var userId = this.dataId; // 从按钮传递的用户ID
            var action = userId ? 'edit' : 'add';

            // 模拟保存操作
            layer.msg(action === 'add' ? '添加成功' : '修改成功', {
                icon: 1,
                time: 1000
            }, function(){
                layer.close(this.index);
                table.reload('userTable');
            });

            return false;
        });

        // 删除用户
        function deleteUser(userId){
            layer.confirm('确定要删除该用户吗？', function(index){
                fetch(requestHost + '/user/delete/' + userId).then(res=>res.json()).then(result=>{
                    if (result.success) {
                        layer.close(index);
                        // 模拟删除操作
                        layer.msg('删除成功', {
                            icon: 1,
                            time: 1000
                        }, function(){
                            table.reload('userTable');
                        });
                    }
                })
            });
        }

        // 审核用户
        function shenheUser(data){
            
            fetch(requestHost + '/user/update', {
                method: 'POST',
                body: JSON.stringify({
                    ...data,
                    isPass: data.isPass === '1' ? '0' : '1'
                }),
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': localStorage.getItem('token')
                }
            }).then(res=>res.json()).then(result=>{
                if (result.success) {
                    // 模拟删除操作
                    layer.msg(data.isPass === '1' ? '不通过' : '通过', {
                        icon: 1,
                        time: 1000
                    }, function(){
                        table.reload('userTable');
                    });
                }
            })
        }
        
        // 切换角色
        function roleUser(data){
            
            fetch(requestHost + '/user/update', {
                method: 'POST',
                body: JSON.stringify({
                    ...data,
                    role: data.role === 'COMMON' ? 'DATA' : 'COMMON'
                }),
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': localStorage.getItem('token')
                }
            }).then(res=>res.json()).then(result=>{
                if (result.success) {
                    // 模拟删除操作
                    layer.msg('切换成功！', {
                        icon: 1,
                        time: 1000
                    }, function(){
                        table.reload('userTable');
                    });
                }
            })
        }
    });
</script>

<script type="text/html" id="tableBar">
    <!-- <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a> -->
    <a class="layui-btn layui-btn-xs" lay-event="shenhe">审核账号</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="role">切换角色</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>

</body>
</html>